package com.weixin.paleituo.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.GoodsDetailPagerAdapter;
import com.weixin.paleituo.adapter.GoodsDetailsRecycleAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.GoodsDetailsBean;
import com.weixin.paleituo.bean.GoodsSelectBean;
import com.weixin.paleituo.bean.SpecificationListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.SelectGoodsEvent;
import com.weixin.paleituo.eventbus.UpdateShopCarNumber;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.BadgeView;
import com.weixin.paleituo.view.HeaderAndFooterWrapper;
import com.weixin.paleituo.view.LoadingPager;
import com.weixin.paleituo.view.SelectGoodsAttriPopuWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

public class GoodsDetailsActivity extends BaseActivity implements ViewPager.OnPageChangeListener {


    @BindView(R.id.iv_back_activity_goods_details)
    ImageView mIvBackActivityGoodsDetails;
    @BindView(R.id.tv_goods_activity_goods_details)
    TextView mTvGoodsActivityGoodsDetails;
    @BindView(R.id.viewline_goods_activity_goods_details)
    View mViewlineGoodsActivityGoodsDetails;
    @BindView(R.id.ll_goods_root_activity_goods_details)
    LinearLayout mLlGoodsRootActivityGoodsDetails;
    @BindView(R.id.tv_details_activity_goods_details)
    TextView mTvDetailsActivityGoodsDetails;
    @BindView(R.id.viewline_details_activity_goods_details)
    View mViewlineDetailsActivityGoodsDetails;
    @BindView(R.id.ll_details_root_activity_goods_details)
    LinearLayout mLlDetailsRootActivityGoodsDetails;
    @BindView(R.id.ll_shop_store_activity_goods_details)
    LinearLayout mLlShopStoreActivityGoodsDetails;
    @BindView(R.id.ll_phone_activity_goods_details)
    LinearLayout mLlPhoneActivityGoodsDetails;
    @BindView(R.id.shop_cart_activity_goods_details)
    LinearLayout mShopCartActivityGoodsDetails;
    @BindView(R.id.tv_joinshopcar_activity_goods_details)
    TextView mTvJoinshopcarActivityGoodsDetails;
    @BindView(R.id.recycle_activity_goods_details)
    RecyclerView mRecycleActivityGoodsDetails;

    private View mHeadView;
    private ViewPager mViewPager;
    private TextView mTvImageIncadtor;
    private TextView mTvGoodsName;
    private TextView mTvSynopsis;

    private TextView mSaledNumber;
    private TextView mSelectConetet, mSelectGoodsNuber;
    private ImageView mIvSelecte;

    private LinearLayoutManager mLinearLayoutManager;
    private LoadingPager mLoadingPager;
    private List<String> bannerUrlLsit = new ArrayList<>();
    private List<String> goodsDetailsList = new ArrayList<>();

    private GoodsDetailPagerAdapter mGoodsDetailPagerAdapter;
    private GoodsDetailsRecycleAdapter mGoodsDetailsRecycleAdapter;
    private SelectGoodsAttriPopuWindow mSelectGoodsAttriPopuWindow;
    private int selectNumber = 1;
    private List<Integer> mIntegerSelct = new ArrayList<>();
    private GoodsSelectBean mGoodsSelectBean;
    private List<SpecificationListBean> mSpecificationList;
    private int goodsId;
    private GoodsDetailsBean mData;
    private LinearLayout mLlvipPriceRoot;
    private TextView mVipMoney;
    private TextView mVipNomalPrice;
    private TextView mNormalMoney;
    private RelativeLayout mRlselectAttrRoot;
    private int mGoodId;

    @Override
    protected void initView() {

        mLoadingPager = new LoadingPager(this,Contans.GOODS_SOLDOUT_TYPE) {
            @Override
            protected void close() {
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(GoodsDetailsActivity.this, R.layout.activity_goods_details);
            }

            @Override
            protected void reLoading() {
                retry();
            }
        };

        setContentView(mLoadingPager);
        //  setContentView(R.layout.activity_goods_details);
        mHeadView = UIUtils.inflate(this, R.layout.layout_goodsdetails_head);
        mViewPager = mHeadView.findViewById(R.id.viewpager_layout_goodsdetails_head);
        mTvImageIncadtor = mHeadView.findViewById(R.id.tv_imageincadtor_layout_goodsdetails_head);
        mTvGoodsName = mHeadView.findViewById(R.id.tv_goodsname_layout_goodsdetails_head);
        mTvSynopsis = mHeadView.findViewById(R.id.tv_synopsis_layout_goodsdetails_head);

        mSaledNumber = mHeadView.findViewById(R.id.tv_saled_layout_goodsdetails_head);
        mSelectConetet = mHeadView.findViewById(R.id.tv_selectedcontent_layout_goodsdetails_head);
        mIvSelecte = mHeadView.findViewById(R.id.iv_select_attri_layout_goodsdetails);
        mSelectGoodsNuber = mHeadView.findViewById(R.id.tv_selectedgoods_number_layout_goodsdetails_head);

        mLlvipPriceRoot = mHeadView.findViewById(R.id.ll_vip_price_root_layout_goodsdetails_head);
        mVipMoney = mHeadView.findViewById(R.id.tv_vipmoney_layout_goodsdetails_head);
        mVipNomalPrice = mHeadView.findViewById(R.id.tv_vipnormal_price_layout_goodsdetails_head);
        mNormalMoney = mHeadView.findViewById(R.id.tv_normalmonety_layout_goodsdetails_head);


        mRlselectAttrRoot = mHeadView.findViewById(R.id.rl_select_attr_root_layout_goodsdetails_head);
        mRlselectAttrRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mSelectGoodsAttriPopuWindow == null) {
                    mSelectGoodsAttriPopuWindow = new SelectGoodsAttriPopuWindow(GoodsDetailsActivity.this,lifecycleSubject);
                    if (mGoodsSelectBean != null ) {
                        mSelectGoodsAttriPopuWindow.setGoodsSelectBean(mGoodsSelectBean,goodsId);
                        if ( mSpecificationList != null && mSpecificationList.size() > 0){

                        mSelectGoodsAttriPopuWindow.setList(mSpecificationList);
                        }
                        mSelectGoodsAttriPopuWindow.setCustomized(mData.getCustomized());
                        mSelectGoodsAttriPopuWindow.showAtLocation(mRecycleActivityGoodsDetails, Gravity.CENTER, 0, 0);

                    }
                }
                else {
                    mSelectGoodsAttriPopuWindow.showAtLocation(mRecycleActivityGoodsDetails, Gravity.CENTER, 0, 0);
                }

            }
        });

        mIvSelecte.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectGoodsAttriPopuWindow == null) {
                    mSelectGoodsAttriPopuWindow = new SelectGoodsAttriPopuWindow(GoodsDetailsActivity.this,lifecycleSubject);
                if (mGoodsSelectBean != null ) {
                    mSelectGoodsAttriPopuWindow.setGoodsSelectBean(mGoodsSelectBean,goodsId);
                    if ( mSpecificationList != null && mSpecificationList.size() > 0){

                        mSelectGoodsAttriPopuWindow.setList(mSpecificationList);
                    }

                    mSelectGoodsAttriPopuWindow.setCustomized(mData.getCustomized());
                    mSelectGoodsAttriPopuWindow.showAtLocation(mRecycleActivityGoodsDetails, Gravity.CENTER, 0, 0);

                }
                }
                else {
                    mSelectGoodsAttriPopuWindow.showAtLocation(mRecycleActivityGoodsDetails, Gravity.CENTER, 0, 0);
                }
            }
        });

    }

    /**
     * 重新加载
     */
    private void retry() {



        Observable<StatusCode<GoodsDetailsBean>> goodsDetailsObservable = ApiUtils.getApi().getGoodsDetails(BaseApplication.getUserId(), BaseApplication.getToken(), mGoodId+"");
        HttpUtil.getInstance().toSubscribe(goodsDetailsObservable, new ProgressSubscriber<GoodsDetailsBean>(this) {
            @Override
            protected void _onNext(StatusCode<GoodsDetailsBean> goodsDetailsBeanStatusCode) {
                mData = goodsDetailsBeanStatusCode.getData();
                List<String> bannerUrl = mData.getBannerUrl();
                List<String> goodsDetailsMobile = mData.getGoodsDetailsMobile();
                mSpecificationList = mData.getSpecificationList();
                if (goodsDetailsBeanStatusCode.isFlag() && bannerUrl != null && bannerUrl.size() > 0 && goodsDetailsMobile != null && goodsDetailsMobile.size() > 0 ) {
                    mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                    bannerUrlLsit.clear();
                    bannerUrlLsit.addAll(bannerUrl);
                    mTvImageIncadtor.setText(1 + "/" + bannerUrlLsit.size());
                    mGoodsDetailPagerAdapter.notifyDataSetChanged();
                    mTvGoodsName.setText(mData.getGoodsName() + "");
                    mTvSynopsis.setText(mData.getGoodsAdWords() + "");
                    double specialSales = mData.getSpecialSales();
                    setShopCarNumber(mData.getCartNum());
                    if (specialSales>0){
                        mLlvipPriceRoot.setVisibility(View.VISIBLE);
                        mVipMoney.setText("楼盘直供价：￥"+UIUtils.getMoney(specialSales));
                        mVipNomalPrice.setText("市场价：￥"+UIUtils.getMoney(mData.getStorePrice()));
                    }else {
                        mNormalMoney.setVisibility(View.VISIBLE);
                        mNormalMoney.setText("市场价：￥"+UIUtils.getMoney(mData.getStorePrice()));
                    }
                  //  mTvgoodsMoney.setText("￥" + mData.getStorePrice() + "");
                    if (mData.getGoodsSalenum() == 0) {
                        mSaledNumber.setVisibility(View.INVISIBLE);
                    } else {
                        mSaledNumber.setVisibility(View.VISIBLE);
                        mSaledNumber.setText("已售" + mData.getGoodsSalenum());
                    }

                    mSelectConetet.setText(StringUtils.isEmpty(mData.getLastName())?"":mData.getLastName());
                    mSaledNumber.setText("数量" + 1);
                    goodsId = mData.getId();

                    //商品详情
                    goodsDetailsList.clear();
                    goodsDetailsList.addAll(goodsDetailsMobile);
                    mGoodsDetailsRecycleAdapter.notifyDataSetChanged();

             mGoodsSelectBean =new GoodsSelectBean();
             mGoodsSelectBean.setStorePrice(mData.getStorePrice());
             mGoodsSelectBean.setSelectedLastName(mData.getLastName());
             mGoodsSelectBean.setSelectNumber(selectNumber);
             mGoodsSelectBean.setSummary(mData.getSummaryList());
                    String coupon = mData.getCoupon();

                    if (!StringUtils.isEmpty(coupon)){

             mGoodsSelectBean.setCoupon(Double.valueOf(mData.getCoupon()));
             }

             mGoodsSelectBean.setGoodsName(mData.getGoodsName());
             mGoodsSelectBean.setGoodsId(mData.getId()+"");
             mGoodsSelectBean.setStoreId(mData.getStoreId()+"");
             mGoodsSelectBean.setStorePrice(mData.getStorePrice());
             mGoodsSelectBean.setVip((specialSales>0)?true:false);
             mGoodsSelectBean.setVipPrice(mData.getSpecialSales());
                } else {
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }
            }
            @Override
            protected void _onError(String message) {

                if (Contans.GOODS_SOLD_OUT.equalsIgnoreCase(message)){

                    mLoadingPager.showPagerView(Contans.STATE_SOLDOUT);


                }else {
                    mLoadingPager.showPagerView(Contans.STATE_ERROR);
                    ToastUtils.makeText(message);
                }

            }
        }, "", lifecycleSubject, false, true);

    }

    private void setShopCarNumber(int cartNum) {

        BadgeView badgeView=new BadgeView(GoodsDetailsActivity.this);
        badgeView.setBackgroundResource(R.drawable.shop_car_number_shape);
        badgeView.setTextColor(UIUtils.getColor(R.color.c_ed5240));
        badgeView.setBadgeMargin(8,0,0,3);
        badgeView.setTextSize(TypedValue.COMPLEX_UNIT_SP,UIUtils.px2dip(UIUtils.getDimens(R.dimen.sp_10)));
         badgeView.setBadgeGravity(Gravity.CENTER | Gravity.TOP);

        badgeView.setBadgeCount(cartNum);
        badgeView.setTargetView(mShopCartActivityGoodsDetails);
    }

    @Override
    protected void initData() {
        super.initData();

        Intent intent = getIntent();
        mGoodId = intent.getIntExtra(Contans.INTENT_DATA, 0);

        EventBus.getDefault().register(this);
        mGoodsDetailPagerAdapter = new GoodsDetailPagerAdapter(this, bannerUrlLsit);
        mViewPager.setAdapter(mGoodsDetailPagerAdapter);
        mViewPager.addOnPageChangeListener(this);

        mGoodsDetailsRecycleAdapter = new GoodsDetailsRecycleAdapter(this, goodsDetailsList);
        HeaderAndFooterWrapper headerAndFooterWrapper = new HeaderAndFooterWrapper(mGoodsDetailsRecycleAdapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        headerAndFooterWrapper.addHeaderView(mHeadView);
        //设置布局管理器
        mRecycleActivityGoodsDetails.setLayoutManager(mLinearLayoutManager);
        //设置adapter
        mRecycleActivityGoodsDetails.setAdapter(headerAndFooterWrapper);
        //设置Item增加、移除动画
        mRecycleActivityGoodsDetails.setItemAnimator(new DefaultItemAnimator());
        mRecycleActivityGoodsDetails.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                LogUtils.i(TAG, "当前最后一个：：" + lastVisibleItemPosition);
                if (lastVisibleItemPosition >= 1) {
                    mTvGoodsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_383838));
                    mViewlineGoodsActivityGoodsDetails.setVisibility(View.INVISIBLE);
                    mTvDetailsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
                    mViewlineDetailsActivityGoodsDetails.setVisibility(View.VISIBLE);

                } else {
                    mTvGoodsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
                    mViewlineGoodsActivityGoodsDetails.setVisibility(View.VISIBLE);
                    mTvDetailsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_383838));
                    mViewlineDetailsActivityGoodsDetails.setVisibility(View.INVISIBLE);
                }
            }
        });
        mSelectGoodsNuber.setText("数量    "+1);

        retry();

    }

    @OnClick(R.id.iv_back_activity_goods_details)
    public void onMIvBackActivityGoodsDetailsClicked() {
        finish();
    }

    @OnClick(R.id.ll_goods_root_activity_goods_details)
    public void onMLlGoodsRootActivityGoodsDetailsClicked() {
        mTvGoodsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
        mViewlineGoodsActivityGoodsDetails.setVisibility(View.VISIBLE);
        mTvDetailsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_383838));
        mViewlineDetailsActivityGoodsDetails.setVisibility(View.INVISIBLE);
        mRecycleActivityGoodsDetails.scrollToPosition(0);


    }
/*    @Subscribe(threadMode = ThreadMode.MAIN)
    public void SelectAttrDissEvent(SelectAttrDissEvent selectAttrDissEvent){
        String lastName = selectAttrDissEvent.getLastName();
        String money = selectAttrDissEvent.getMoney();
        int number = selectAttrDissEvent.getNumber();

        if (!StringUtils.isEmpty(lastName)){
            mSelectConetet.setText(lastName);
        }
        if (!StringUtils.isEmpty(money)){

            mTvgoodsMoney.setText("￥" + money);
        }
        if (number!=0){
            mSelectGoodsNuber.setText("数量    "+number);
        }




    }*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void selectGoodsEvent(SelectGoodsEvent selectGoodsEvent){

    double price = selectGoodsEvent.getPrice();
    int selectNum = selectGoodsEvent.getSelectNum();
    double vipPrice = selectGoodsEvent.getVipPrice();
    boolean isvip = selectGoodsEvent.isIsvip();
    String selectInfo = selectGoodsEvent.getSelectInfo();

    if (isvip){
        mLlvipPriceRoot.setVisibility(View.VISIBLE);
        mVipMoney.setText("楼盘直供价：￥"+UIUtils.getMoney(vipPrice));
        mVipNomalPrice.setText("价格：￥"+UIUtils.getMoney(price));
    }else {
        mNormalMoney.setVisibility(View.VISIBLE);
        mNormalMoney.setText("价格：￥"+UIUtils.getMoney(price));
    }
    mSelectGoodsNuber.setText("数量    "+selectNum);

    mSelectConetet.setText(StringUtils.isEmpty(selectInfo)?"":selectInfo);
}

    @OnClick(R.id.ll_details_root_activity_goods_details)
    public void onMLlDetailsRootActivityGoodsDetailsClicked() {
        mTvGoodsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_383838));
        mViewlineGoodsActivityGoodsDetails.setVisibility(View.INVISIBLE);
        mTvDetailsActivityGoodsDetails.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
        mViewlineDetailsActivityGoodsDetails.setVisibility(View.VISIBLE);
        mRecycleActivityGoodsDetails.scrollToPosition(1);
    }

    @OnClick(R.id.ll_shop_store_activity_goods_details)
    public void onMLlShopStoreActivityGoodsDetailsClicked() {

        if (mData.getStoreId()==0){
            ToastUtils.makeText("没有店铺");
            return;
        }
        GoodsStoreActivity.startActivity(this,mData.getStoreId());
    }
    @OnClick(R.id.ll_phone_activity_goods_details)
    public void onMLlPhoneActivityGoodsDetailsClicked() {
        String storeTelephone = mData.getStoreTelephone();
        if (!StringUtils.isEmpty(storeTelephone)){
            try {
                Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + storeTelephone));
                startActivity(dialIntent);
            }catch (Exception e){
            }
        }else {
            ToastUtils.makeText("没有电话");
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateShopCarNumber(UpdateShopCarNumber updateShopCarNumber){

        int number = updateShopCarNumber.getNumber();
        setShopCarNumber(number);

    }

    @OnClick(R.id.shop_cart_activity_goods_details)
    public void onMShopCartActivityGoodsDetailsClicked() {

        if (BaseApplication.isLoginSuccess){

        ShopCarActivity.startActivity(this);
        }else {
            LoginActivity.startActivity(this,true);
        }
    }

    @OnClick(R.id.tv_joinshopcar_activity_goods_details)
    public void onMTvJoinshopcarActivityGoodsDetailsClicked() {
        if (mSelectGoodsAttriPopuWindow == null) {
            mSelectGoodsAttriPopuWindow = new SelectGoodsAttriPopuWindow(GoodsDetailsActivity.this,lifecycleSubject);
            if (mGoodsSelectBean != null) {
                mSelectGoodsAttriPopuWindow.setGoodsSelectBean(mGoodsSelectBean,goodsId);
                if ( mSpecificationList != null && mSpecificationList.size() > 0){

                    mSelectGoodsAttriPopuWindow.setList(mSpecificationList);
                }

                mSelectGoodsAttriPopuWindow.setCustomized(mData.getCustomized());
                mSelectGoodsAttriPopuWindow.showAtLocation(mRecycleActivityGoodsDetails, Gravity.CENTER, 0, 0);
            }
        }
        else {
            mSelectGoodsAttriPopuWindow.showAtLocation(mRecycleActivityGoodsDetails, Gravity.CENTER, 0, 0);
        }


    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        mTvImageIncadtor.setText(position + 1 + "/" + bannerUrlLsit.size());

    }


    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public static void startActivity(Context context,int goodsId) {

        Intent intent = new Intent(context, GoodsDetailsActivity.class);
        intent.putExtra(Contans.INTENT_DATA,goodsId);
        context.startActivity(intent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
